<?php

namespace App\Models\Applet\User;

use Illuminate\Support\Facades\DB;

class UserSponsorModel extends BaseUserModel
{
    protected $table = 'user_sponsor';

    const STATUS_DEFAULT      = 0; // 未出栏
    const STATUS_END          = 1; // 已出栏
    const STATUS_RECYCLING    = 2; // 回收中
    const STATUS_RECYCLED     = 3; // 已回收
    const STATUS_SLAUGHTERING = 4; // 宰杀中
    const STATUS_SLAUGHTERED  = 5; // 已宰杀


    /**
     * 根据用户id获取总条数
     * @param int $userId
     * @param array $params
     * @return int
     */
    public function getTotalByUserId(int $userId, array $params): int
    {
        $query = $this->where('user_id', $userId)
                      ->where('deleted', self::DELETED_NO);

        // 状态 0 未出栏 1 已出栏 2 回收中 3 已回收 4 宰杀中 5 已宰杀
        if (isset($params['status'])) {
            $query = $query->where('status', $params['status']);
        }

        // 价格排序
        if (isset($params['priceSort'])) {
            $query = $query->orderBy('price', $params['priceSort']);
        }

        // 时长排序
        if (isset($params['timeSort'])) {
            $query = $query->orderBy('created_at', $params['timeSort']);
        }

        return $query->count();
    }

    /**
     * 根据用户id获取总条数
     * @param int $userId
     * @return array
     */
    public function getTotalQuantityByUserId(int $userId): array
    {
        return $this->select([DB::raw('sum(quantity) as totalQuantity')])
            ->where('user_id', $userId)
            ->where('deleted', self::DELETED_NO)
            ->get()
            ->toArray();
    }

    /**
     * 根据用户id获取列表
     * @param int $userId
     * @param array $params
     * @param array $fields
     * @return array
     * @params array $params
     */
    public function getItemsByUserId(int $userId, array $params, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $query = $this->select($fields)
                      ->where('user_id', $userId)
                      ->where('deleted', self::DELETED_NO);

        // 状态 0 未出栏 1 已出栏 2 回收中 3 已回收 4 宰杀中 5 已宰杀
        if (isset($params['status'])) {
            $query = $query->where('status', $params['status']);
        }

        // 价格排序
        if (isset($params['priceSort'])) {
            $query = $query->orderBy('price', $params['priceSort']);
        }

        // 时长排序
        if (isset($params['timeSort'])) {
            $query = $query->orderBy('created_at', $params['timeSort']);
        }

        return $query->orderBy('id', 'desc')
                     ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                     ->limit(PAGE_SIZE)
                     ->get()
                     ->toArray();
    }

    /**
     * 根据id和用户id获取列表
     * @param int $id
     * @param int $userId
     * @param array $fields
     * @return array
     */
    public function getItemsByIdAndUserId(int $id, int $userId, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
                       ->where('id', $id)
                       ->where('user_id', $userId)
                       ->where('deleted', self::DELETED_NO)
                       ->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 认养总条数
     *
     * @param array $params
     * @return int
     */
    public function total(array $params): int
    {
        $query = $this;
        if (!empty($params['keyword'])) {
            $whereRaw = '(nickname like "%' . $params['keyword'] . '%"' .
                        ' or phone like "%' . $params['keyword'] . '%")';
            if (is_numeric($params['keyword'])) {
                $whereRaw = trim($whereRaw, ')');
                $whereRaw .= ' or cast(user_sponsor.id as char) like "%' . $params['keyword'] . '%")';
            }
            $query = $query->whereRaw($whereRaw);
        }

        if (isset($params['status']) && $params['status'] != -1) {
            $query = $query->where('user_sponsor.status', $params['status']);
        }

        return $query->join('users', 'users.id', '=', 'user_sponsor.user_id')
                     ->where('user_sponsor.deleted', self::DELETED_NO)->count();
    }

    /**
     * 认养列表
     * @param array $params
     * @param array $fields
     * @return array
     */
    public function list(array $params, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $query = $this;
        if (!empty($params['keyword'])) {
            $whereRaw = '(nickname like "%' . $params['keyword'] . '%"' .
                        ' or phone like "%' . $params['keyword'] . '%")';
            if (is_numeric($params['keyword'])) {
                $whereRaw = trim($whereRaw, ')');
                $whereRaw .= ' or cast(user_sponsor.id as char) like "%' . $params['keyword'] . '%")';
            }
            $query = $query->whereRaw($whereRaw);
        }

        if (isset($params['status']) && $params['status'] != -1) {
            $query = $query->where('user_sponsor.status', $params['status']);
        }

        return $query->select($fields)
                     ->join('users', 'users.id', '=', 'user_sponsor.user_id')
                     ->where('user_sponsor.deleted', self::DELETED_NO)
                     ->orderBy('id', 'desc')
                     ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                     ->limit(PAGE_SIZE)
                     ->get()
                     ->toArray();
    }

    /**
     * 根据牧场id查询userSponsorIds
     * @param array $params
     * @param array $fields
     * @return array
     */
    public function storeList(array $params, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $query = $this->select($fields);

        if (!empty($params['status'])) {
            switch ($params['status']) {
                case 10: // 养殖中
                    $query = $query->where('status', UserSponsorModel::STATUS_DEFAULT);
                    break;
                case 20: // 产奶中
                    $query = $query->where('status', UserSponsorModel::STATUS_END);
                    break;
                case 30: // 待处理
                    $query = $query->whereIn('status', [
                        UserSponsorModel::STATUS_RECYCLING,
                        UserSponsorModel::STATUS_SLAUGHTERING
                    ]);
                    break;
                case 40: // 已结束
                    $query = $query->whereIn('status', [
                        UserSponsorModel::STATUS_RECYCLED,
                        UserSponsorModel::STATUS_SLAUGHTERED
                    ]);
                    break;
            }
        }
        return $query->where('ranch_id', $params['ranchId'])
                     ->where('deleted', self::DELETED_NO)
                     ->orderBy('id', 'desc')
                     ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                     ->limit(PAGE_SIZE)
                     ->get()
                     ->toArray();
    }

    /**
     * 根据订单ids获取列表
     * @return void
     */
    public function getItemsByOrderIds(array $orderIds, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
                    ->where('order_id', $orderIds)
                    ->where('deleted', self::DELETED_NO)
                    ->get()
                    ->toArray();
    }
}
